import axios from 'axios';
import router from '../router';
import { Message } from 'element-ui';

const service = axios.create({
    baseURL: 'http://localhost:8989/',
    // timeout: 30000
});

service.interceptors.request.use(
    config => {
        const token = sessionStorage.getItem("ClientToken")
        if (token) {  // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
            config.headers.ClientToken = token;
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.data.code === 2) {
            sessionStorage.removeItem("ClientToken");
            sessionStorage.removeItem("userName");
            router.push({
                path: '/login'
            })
        }
        return response.data;
    },
    error => {
        console.log(error); 
        let msg;
        if (error.response.data.msg === undefined || error.response.data.msg === null) {
            msg = "系统错误！"
        } else {
            msg = error.response.data.msg
        }
        Message.error({
            showClose: true,
            message: msg
          })
        return Promise.reject();
    }
);

export default service;
